package com.qiuzhiyi.fragment;

import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.li.utils.VerifyUtil;
import com.qiuzhiyi.R;
import com.qiuzhiyi.base.QZYBaseFragment;
import com.qiuzhiyi.cache.HumanCache;
import com.qiuzhiyi.item.BaseItem;
import com.qiuzhiyi.item.HumanItem;
import com.qiuzhiyi.net.ObservableHelper;
import com.qiuzhiyi.net.RetrofitHelper;
import com.qiuzhiyi.net.SelectorObserver;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.disposables.Disposable;

/**
 * Author: Li
 * Date: 2017/11/14 0014
 * Description:
 */

public class MsgLoginFragment extends QZYBaseFragment {

    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.et_msg)
    EditText mEtMsg;
    @BindView(R.id.txt_msg)
    TextView mTxtMsg;
    @BindView(R.id.txt_login)
    TextView mTxtLogin;

    private Count mCount;
    private EventHandler mEventHandler;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_login_msg;

    }

    @Override
    protected void initSth() {
        super.initSth();
        mCount = new Count(60 * 1000 + 16, 1000);
        try {


            mEventHandler = new EventHandler() {
                @Override
                public void afterEvent(int event, int result, Object data) {
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissLoadingDialog();
                            }
                        });
                    }

                    if (result == SMSSDK.RESULT_COMPLETE) {
                        //回调完成
                        if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                            //提交验证码成功
                            if (getActivity() != null) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        login(mEtPhone.getText().toString());
                                    }
                                });
                            }
                        } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                            //获取验证码成功
                            mCount.start();
                            if (getActivity() != null) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        showToast("获取验证码成功");

                                    }
                                });
                            }
                        }
                    } else {
                        if (getActivity() != null) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showToast("请正确填写手机号和验证码");
                                }
                            });
                        }

                    }

                }
            };
        } catch (Exception e) {
            Log.e("tag", "initSth: ");
        }
        SMSSDK.registerEventHandler(mEventHandler);

    }

    @OnClick({R.id.txt_msg, R.id.txt_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_msg:
                if (VerifyUtil.checkPhone(mEtPhone.getText().toString())) {
                    SMSSDK.getVerificationCode("+86", mEtPhone.getText().toString());
                    showLoadingDialog("正在获取验证码");
                } else {
                    showToast("请填写正确手机号");
                }

                break;
            case R.id.txt_login:
                SMSSDK.submitVerificationCode("+86", mEtPhone.getText().toString(), mEtMsg.getText().toString());
                showLoadingDialog("正在验证");
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mCount.cancel();
        SMSSDK.unregisterEventHandler(mEventHandler);
    }

    /**
     * 登录
     *
     * @param account 账号
     */
    private void login(String account) {
        Map<String, String> map = new HashMap<>();
        map.put("humanAccount", account);
        map.put("loginStatus", "1");
        ObservableHelper.createObservable(RetrofitHelper.createService().loginWithPwd(map))
                .subscribe(new SelectorObserver<BaseItem<HumanItem>>() {
                    @Override
                    protected void onErrorCodeInfo(String code, String info) {
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseItem<HumanItem> humanItemBaseItem) {
                        HumanItem item = humanItemBaseItem.getObjValue();
                        HumanCache.saveHumanInfo(mContext, item);

                        showToast("登陆成功");
                        getActivity().finish();
//                        startThenFinish(MainActivity.class);
                    }

                    @Override
                    protected void onFinish() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog("正在登录");
                    }
                });

    }

    private class Count extends CountDownTimer {

        Count(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);

        }

        @Override
        public void onTick(long millisUntilFinished) {
            mTxtMsg.setEnabled(false);
            String txt = String.valueOf(millisUntilFinished / 1000) + "秒后重新获取";
            mTxtMsg.setText(txt);
        }

        @Override
        public void onFinish() {
            mTxtMsg.setEnabled(true);
            mTxtMsg.setText("重新获取验证码");
        }
    }
}
